﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialHelper
{
    public partial class Form1 : Form
    {
        private SerialPort serialPort = new SerialPort();
        public Form1()
        {
            InitializeComponent();
            Inint();
            
        }

        public void Inint()
        {
            var list = SerialPort.GetPortNames();
            if (list.Length > 0)
            {
                foreach (var item in list)
                {
                    PortList.Items.Add(item);
                }
                PortList.SelectedIndex = 0;

            }
            else
            {
                MessageBox.Show("未发现端口，请检查");
                Openport.Enabled = false;
            }
            PaudList.Items.Add("9600");
            PaudList.Items.Add("19200");
            string[] databitslistadd = { "6", "7", "8" };
            DatabitsList.Items.AddRange(databitslistadd);
            string[] parityListadd = { "NONE", "EVEN", "Odd" };
            ParityList.Items.AddRange(parityListadd);
            StopbitsList.Items.Add("1");
            StopbitsList.Items.Add("2");
            PaudList.SelectedIndex = 0;
            DatabitsList.SelectedIndex = 2;
            ParityList.SelectedIndex = 0;
            StopbitsList.SelectedIndex = 0;
            ReciveData.AutoSize = false;
            ReciveData.Height = 120;
            SendData.AutoSize = false;
            SendData.Height = 120;


        }

        public void SetSerialPort(SerialPort serialport)
        {
            serialport.PortName = PortList.SelectedItem.ToString();
            serialport.BaudRate = int.Parse(PaudList.SelectedItem.ToString());
            switch (ParityList.SelectedItem.ToString())
            {
                case "NONE":
                    serialport.Parity = Parity.None;
                    break;
                case "EVEN":
                    serialport.Parity = Parity.Even;
                    break;
                case "Odd":
                    serialport.Parity = Parity.Odd;
                    break;
                default: break;
            }
            serialport.DataBits = int.Parse(DatabitsList.SelectedItem.ToString());
            switch (StopbitsList.SelectedItem.ToString())
            {
                case "1":
                    serialport.StopBits = StopBits.One;
                    break;
                case "2":
                    serialport.StopBits = StopBits.Two;
                    break;
                default:
                    break;
            }

        }
        private void Openport_Click(object sender, EventArgs e)
        {
            try
            {
                if (Openport.Text.Trim() == "打开串口")
                {

                    SetSerialPort(serialPort);
                    serialPort.Encoding = Encoding.GetEncoding("utf-8");//打开串口前，设置文本编码
                    serialPort.Open();
                    serialPort.DataReceived += SerialPort_DataReceived;
                    MessageBox.Show("打开串口成功");
                    Openport.Text = "关闭串口";
                    Status.BackColor = Color.Green;
                }
                else
                {
                    serialPort.Close();
                    MessageBox.Show("关闭串口成功！");
                    Openport.Text = "打开串口";
                }

            }
            catch (Exception exce)
            {
                MessageBox.Show(exce.Message);
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            ReciveDataMethod();
        }

        public void DataSend(string message)
        {
            if (serialPort.IsOpen)
            {
                if (SendData.Text.Length > 0)
                {
                    serialPort.Write(message);
                    MessageBox.Show("发送成功！");
                }
                else MessageBox.Show("发送数据不能为空！");
                
            }
            else MessageBox.Show("请先打开串口！");
        }
        public void ReciveDataMethod()
        {   

            byte[] data = new byte[serialPort.BytesToRead];
            serialPort.Read(data, 0, data.Length);
            string recivedata = Encoding.UTF8.GetString(data);
            Invoke(new Action(() => { ReciveData.Text += recivedata; }));
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
            DataSend(SendData.Text.Trim());
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            SendData.Text = string.Empty;
            ReciveData.Text = string.Empty;
        }

    }
}
